<template>
    <div id="container" ref="container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';

const container = ref<HTMLElement>();
let editor: monaco.editor.IStandaloneCodeEditor | null = null;
let webviewMessageHandler: ((event: any) => void) | null = null;

// 配置选项
let editorTheme = 'vs-light';
let editorLanguage = 'cpp';

window.MonacoEnvironment = {
    getWorker(_workerId: any, _label: string) {
        return new editorWorker();
    }
};

onMounted(() => {
    initEditor();
    window.editor = editor;
});

onBeforeUnmount(() => {
    // 清理资源
    if (editor) editor.dispose();
    if (webviewMessageHandler && window.chrome.webview) {
        window.chrome.webview.removeEventListener('message', webviewMessageHandler);
    }
});

const initEditor = () => {
    editor = monaco.editor.create(container.value!, {
        value: '#include <iostream>\r\nusing namespace std;\r\nint main(){\r\n    \r\n    return 0;\r\n}',
        language: editorLanguage,
        fontSize: 18,
        formatOnPaste: true,
        fontFamily: 'Cascadia Code',
        minimap: { enabled: false },
        automaticLayout: false,
        theme: editorTheme, //'vs-light',
        scrollbar: {
            vertical: 'auto',
            verticalScrollbarSize: 8,
            
            verticalSliderSize: 6,
            horizontal: 'hidden'
        },
        renderLineHighlight: 'all', // 当前行突出显示方式
        // roundedSelection: true,
        // scrollBeyondLastLine: false,
        contextmenu: false,
    });

    // 注册 WebView2 消息监听器
    if (window.chrome && window.chrome.webview) {
        webviewMessageHandler = (event) => handleWebviewMessage(event);
        window.chrome.webview.addEventListener('message', webviewMessageHandler);

        // 通知宿主前端已准备就绪
        sendMessageToHost({ type: 'vueMounted' });
    }

    // 可选：编辑器内容变化时通知宿主（按需启用）
    /*
    editor.onDidChangeModelContent(() => {
        sendMessageToHost({
            type: 'codeChange',
            content: editor.getValue()
        });
    });
    */
}

// 发送消息到 WinUI3 宿主
const sendMessageToHost = (message: any) => {
    if (window.chrome && window.chrome.webview) {
        window.chrome.webview.postMessage(JSON.stringify(message));
    }
};

// 接收来自宿主消息
const handleWebviewMessage = (event: any) => {
    try {
        const data = JSON.parse(event.data);

        // 处理不同指令
        switch (data.command) {
            case 'updateCode':
                if (editor) {
                    editor.setValue(data.content);
                }
                break;

            case 'getCode':
                if (editor) {
                    sendMessageToHost({
                        type: 'currentCode',
                        content: editor.getValue()
                    });
                }
                break;

            // 添加其他命令处理...
            case 'changeTheme':
                monaco.editor.setTheme(data.theme);
                break;
        }
    } catch (error) {
        console.error('Error parsing message', error);
    }
};

// 设置ResizeObserver监听容器
let resizeTimer: ReturnType<typeof setTimeout> | null = null;
const resizeObserver = ref<ResizeObserver | null>(null);
resizeObserver.value = new ResizeObserver(() => {
    clearTimeout(resizeTimer!);
    resizeTimer = setTimeout(() => {
        console.log("layout");
        editor?.layout();
    }, 300);
});
// 监听容器
let observerContainer = document.querySelector('body');
// 开始监听容器
if (observerContainer) {
    resizeObserver.value.observe(observerContainer);
}

// 声明全局接口
declare global {
    interface Window {
        editor: monaco.editor.IStandaloneCodeEditor | null;
        chrome: {
            webview: {
                postMessage(message: string): void;
                addEventListener(eventName: string, handler: (event: any) => void): void;
                removeEventListener(eventName: string, handler: (event: any) => void): void;
            };
        };
    }
}
</script>

<style scoped>
#container {
    width: 100% !important;
    height: 100%;
}
</style>
